package com.xingzhi.crm.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zxcms.user.annotation.AuthCheck;
import com.zxcms.user.bean.*;
import com.zxcms.user.consts.Auth;
import com.zxcms.user.consts.Const;
import com.zxcms.user.consts.MsgConst;
import com.zxcms.user.dto.ResponseBaseDTO;
import com.zxcms.user.service.CmsService;
import com.zxcms.user.service.LmsService;
import com.zxcms.user.service.UserService;
import com.zxcms.user.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by daniel.luo on 2018/6/5.
 */
@RestController
public class CmsController {

    @Autowired
    UserService userService;

    @Autowired
    CmsService cmsService;

    @Autowired
    TokenUtil tokenUtil;

    @AuthCheck(Auth.NEED_LOGIN)
    @PostMapping("/manager/catalog/upload")
    public ResponseBaseDTO uploadCatalog(@RequestBody JSONObject jo, HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        JSONObject data = jo.getJSONObject("data");
        String cid = data.getString("cid");
        String catalog = data.getString("detail");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        DeviceInfo deviceInfo = IpUtil.getDeviceInfo(request);
        JSONObject content = new JSONObject();
        CourseGet courseGet = userService.getCourseByCid(cid);
        CourseLen len = new CourseLen();
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("uid", uid);
        mapParam.put("cid", cid);
        mapParam.put("catalog", catalog);
        int ret = userService.updateCatalog(mapParam);
        if (1 == ret) {
            content.put("cid", cid);
            content.put("name", courseGet.getCourse_name());
            content.put("code", courseGet.getCode());
            mapParam.put("content", content.toString());
            mapParam.put("type", "3");
            if (StringUtils.isEmpty(userService.getLastCreateTime(mapParam))) {
                String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "编辑了课件", "3", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
            } else {
                if (TimeUtil.getDateTime(60).compareTo(userService.getLastCreateTime(mapParam)) > 0) {
                    String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                    String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "编辑了课件", "3", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                    userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
                }
            }
            if (!"[]".equals(catalog))
                len = cmsService.getTotalLenByCid(cid);
            mapParam.put("len", String.valueOf(len.getTotal_len()));
            mapParam.put("num", String.valueOf(len.getTotal_num()));
            cmsService.updateCourseTotalLen(mapParam);
            dto.setDesc("更新目录成功");
            dto.setStatus(MsgConst.UPDATE_CATALOG_SUCCESS);
            dto.setSuccess(true);
        } else {
            dto.setDesc("更新目录失败");
            dto.setStatus(MsgConst.UPDATE_CATALOG_FAILED);
            dto.setSuccess(false);
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/catalog/get")
    public ResponseBaseDTO getCatalog(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("cid");
        if (StringUtils.isEmpty(cid)) {
            dto.setDesc("缺失课程参数");
            dto.setStatus(MsgConst.GET_CATALOG_FAILED);
            dto.setSuccess(false);
        } else {
            dto.setData(userService.getCatalog(cid));
            dto.setDesc("获取课程成功");
            dto.setStatus(MsgConst.GET_CATALOG_SUCCESS);
            dto.setSuccess(true);
        }
        return dto;
    }

    /**
     * 获取课程管理日志
     *
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/manager/course_log/all")
    public ResponseBaseDTO getAllCourseChangeLog(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("id");
        List<CourseChangeLog> listRet = userService.getAllCourseChangeLog(cid);
        dto.setData(listRet);
        dto.setDesc("获取课程日志成功");
        dto.setStatus(MsgConst.GET_ALL_COURSE_CHANGE_LOG_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }

    /**
     * 教研重新编辑
     *
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/manager/course/re_edit")
    public ResponseBaseDTO updateCourseReedit(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("cid");
        int ret = userService.updateCourseReedit(cid);
        if (1 == ret) {
            dto.setDesc("操作成功");
            dto.setStatus(MsgConst.UPDATE_COURSE_REEDIT_SUCCESS);
            dto.setSuccess(true);
        } else {
            dto.setDesc("操作失败");
            dto.setStatus(MsgConst.UPDATE_COURSE_REEDIT_FAILED);
            dto.setSuccess(false);
        }
        return dto;
    }

    /**
     * 确认提交课件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/manager/course/submit")
    @ResponseBody
    public ResponseBaseDTO confirmSubmit(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("cid");
        if (StringUtils.isEmpty(cid)) {
            dto.setDesc("提交课件不能为空");
            dto.setStatus(MsgConst.CONFIRMSUBMIT_NOT_NULL);
            dto.setSuccess(false);
            return dto;
        }
        int ret = userService.confirmSubmit(cid);
        if (1 == ret) {
            dto.setDesc("操作成功");
            dto.setStatus(MsgConst.CONFIRMSUBMIT_SUCCESS);
            dto.setSuccess(true);
        } else {
            dto.setDesc("操作失败");
            dto.setStatus(MsgConst.CONFIRMSUBMIT_FAILED);
            dto.setSuccess(true);
        }
        return dto;
    }


    @AuthCheck(Auth.NEED_LOGIN)
    @PostMapping("/manager/material/add")
    public ResponseBaseDTO addMaterial(@RequestBody JSONObject jo, HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        JSONObject data = jo.getJSONObject("data");
        String cid = data.getString("cid");
        String ware_name = data.getString("name");
        String url = Const.DOMAIN + data.getString("key");
        String type = data.getString("type");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        System.out.println("source key : " + data.getString("key"));
        // TODO verify auth
        boolean flag = userService.checkAddMaterial(cid, ware_name, url, type);
        if (!flag) {
            dto.setDesc("信息不全");
            dto.setStatus(MsgConst.ADD_MATERIAL_FAILED);
            dto.setSuccess(false);
            return dto;
        } else {
            int len = QiNiuUtil.getVedioLength(data.getString("key"));
            if (-1 == len) {
                dto.setDesc("获取视频长度失败");
                dto.setStatus(MsgConst.ADD_MATERIAL_FAILED);
                dto.setSuccess(false);
            } else {
                String lenStr = String.valueOf(len);
                String ware_id = HashUtil.generateSerialNum(uid, "2" + HashUtil.generateRandomNum(10));
                Map<String, String> mapParam = new HashMap<String, String>();
                mapParam.put("ware_id", ware_id);
                mapParam.put("cid", cid);
                mapParam.put("ware_name", ware_name);
                mapParam.put("url", url);
                mapParam.put("len", lenStr);
                mapParam.put("type", type);
                mapParam.put("uid", uid);
                String curTime = TimeUtil.getDateTime();
                mapParam.put("update_time", curTime);
                mapParam.put("create_time", curTime);
                int ret = userService.addMaterial(mapParam);
                if (1 == ret) {
                    // encrypt
                    /*
                    Map<String, String> mapEncrypt = QiNiuUtil.encryptOneVideo(data.getString("key"));
                    if (null != mapEncrypt) {
                        cmsService.setEncryptInfo(mapEncrypt);
                    }
                    */
                    dto.setDesc("添加成功");
                    dto.setStatus(MsgConst.ADD_MATERIAL_SUCCESS);
                    dto.setSuccess(true);
                    dto.setData(ware_id);
                } else {
                    dto.setDesc("添加失败");
                    dto.setStatus(MsgConst.ADD_MATERIAL_FAILED);
                    dto.setSuccess(false);
                }
            }
            return dto;
        }
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/course_ware/reencrypt")
    @ResponseBody
    public ResponseBaseDTO reEncryptCourseWare(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String ware_id = request.getParameter("ware_id");
        if (StringUtils.isEmpty(ware_id)) {
            dto.setSuccess(false);
            dto.setDesc("缺少参数");
            dto.setStatus(MsgConst.RE_ENCRYPT_FAILED);
        } else {
            CourseWareModel courseWareModel = cmsService.getCourseWareById(ware_id);
            String key = courseWareModel.getUrl().replace(Const.DOMAIN, "");
            Map<String, String> mapEncrypt = QiNiuUtil.encryptOneVideo(key);
            if (null != mapEncrypt) {
                mapEncrypt.put("ware_id", ware_id);
                cmsService.updateEncryptTime(mapEncrypt);
                dto.setSuccess(true);
                dto.setDesc("正在努力加密");
                dto.setStatus(MsgConst.RE_ENCRYPT_SUCCESS);
            } else {
                dto.setSuccess(false);
                dto.setDesc("加密失败");
                dto.setStatus(MsgConst.RE_ENCRYPT_FAILED);
            }
        }
        return dto;
    }


    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/material/all")
    @ResponseBody
    public ResponseBaseDTO getAllMaterial(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("cid");
        List<CourseWareModel> listRet = userService.getAllCourseWareByCid(cid);
        // set encrypt key
        /*
        listRet.stream().forEach(x -> x.setEncrypt_key(Const.DOMAIN + x.getEncrypt_key()));
        */
        dto.setData(listRet);
        dto.setSuccess(true);
        dto.setDesc("获取素材列表成功");
        dto.setStatus(MsgConst.GET_ALL_MATERIAL_ONEC_SUCCESS);
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @PostMapping("/manager/node_detail/add")
    public ResponseBaseDTO addNodeDetail(@RequestBody JSONObject jo, HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        JSONObject data = jo.getJSONObject("data");
        String cid = data.getString("cid");
        String node_id = data.getString("node_id");
        String ware_id = data.getString("ware_id");
        String desc_info = data.getString("desc_info");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        DeviceInfo deviceInfo = IpUtil.getDeviceInfo(request);
        JSONObject content = new JSONObject();
        CourseGet courseGet = userService.getCourseByCid(cid);
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("node_id", node_id);
        mapParam.put("cid", cid);
        mapParam.put("ware_id", ware_id);
        mapParam.put("desc_info", desc_info);
        mapParam.put("uid", uid);
        String curTime = TimeUtil.getDateTime();
        mapParam.put("update_time", curTime);
        mapParam.put("create_time", curTime);
        // TODO verify auth
        int ret = 0;
        if (userService.checkNodeDetailExistById(node_id))
            ret = userService.updateNodeDetail(mapParam);
        else ret = userService.addNodeDetail(mapParam);
        if (1 == ret) {
            content.put("cid", cid);
            content.put("name", courseGet.getCourse_name());
            content.put("code", courseGet.getCode());
            mapParam.put("content", content.toString());
            mapParam.put("type", "3");
            if (StringUtils.isEmpty(userService.getLastCreateTime(mapParam))) {
                String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "编辑了课件", "3", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
            } else {
                if (TimeUtil.getDateTime(60).compareTo(userService.getLastCreateTime(mapParam)) > 0) {
                    String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                    String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "编辑了课件", "3", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                    userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
                }
            }
            CourseLen len = cmsService.getTotalLenByCid(cid);
            mapParam.put("len", String.valueOf(len.getTotal_len()));
            mapParam.put("num", String.valueOf(len.getTotal_num()));
            cmsService.updateCourseTotalLen(mapParam);
            dto.setDesc("添加成功");
            dto.setStatus(MsgConst.ADD_MATERIAL_DETAIL_SUCCESS);
            dto.setSuccess(true);
        } else {
            dto.setDesc("添加失败");
            dto.setStatus(MsgConst.ADD_MATERIAL_DETAIL_FAILED);
            dto.setSuccess(false);
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/node_detail/get")
    public ResponseBaseDTO getNodeDetail(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String node_id = request.getParameter("nid");
        JSONObject resJo = new JSONObject();
        NodeDetail nodeDetail = userService.getNodeDetail(node_id);
        if (null == nodeDetail) resJo.put("is_have", false);
        else {
            resJo.put("is_have", true);
            resJo.put("detail", nodeDetail);
        }
        dto.setData(resJo);
        dto.setSuccess(true);
        dto.setDesc("获取节点详情成功");
        dto.setStatus(MsgConst.GET_NODE_DETAIL_SUCCESS);
        return dto;
    }

    /**
     * 获取所有课程
     */
    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/course_m/all")
    @ResponseBody
    public ResponseBaseDTO getCourseByManager(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String status = request.getParameter("status");
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        String sign = request.getParameter("sign");
        Map<String, String> mapParam = new HashMap<String, String>();
        if (sign != null) {
            if (Integer.parseInt(sign) > 0) {
                String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
                mapParam.put("uid", uid);
            }
            mapParam.put("status", status);
            mapParam.put("sign", sign);
        }
        int page = StringUtils.isEmpty(pageStr) ? 1 : Integer.parseInt(pageStr);
        int size = StringUtils.isEmpty(sizeStr) ? 10 : Integer.parseInt(sizeStr);
        List<CourseAll> listRet = userService.getCourseAllM(mapParam, page, size);
        PagedResult<CourseAll> pagedResult = BeanUtil.toPagedResult(listRet);
        dto.setData(pagedResult);
        dto.setDesc("获取课程列表成功");
        dto.setStatus(MsgConst.GET_ALL_COURSEMANAGER_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }

    /**
     * cms获取所有课程
     */
    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/course_cms/all")
    @ResponseBody
    public ResponseBaseDTO getCourseAllCms(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        String status = request.getParameter("status");
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        int page = StringUtils.isEmpty(pageStr) ? 1 : Integer.parseInt(pageStr);
        int size = StringUtils.isEmpty(sizeStr) ? 10 : Integer.parseInt(sizeStr);
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("uid", uid);
        mapParam.put("status", status);
        mapParam.put("starttime", starttime);
        mapParam.put("endtime", endtime);
        List<CourseAllCms> listRet = userService.getCourseAllCms(mapParam, page, size);
        PagedResult<CourseAllCms> pagedResult = BeanUtil.toPagedResult(listRet);
        dto.setData(pagedResult);
        dto.setDesc("获取课程列表成功");
        dto.setStatus(MsgConst.GET_ALL_COURSCMS_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }

    /*
     *
     * 修改课程信息
     * */
    @PostMapping("/manager/course/update")
    @ResponseBody
    public ResponseBaseDTO updateCourseShot(@RequestBody JSONObject jo, HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        JSONObject data = jo.getJSONObject("data");
        String cid = data.getString("cid");
        String cname = data.getString("name");
        String desc_info = data.getString("desc_info");
        String key = data.getString("key");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        String img_url = Const.DOMAIN + key;
        CourseGet courseGet = userService.getCourseByCid(cid);
        String code = courseGet.getCode();
        String update_time = TimeUtil.getDateTime();
        DeviceInfo deviceInfo = IpUtil.getDeviceInfo(request);
        JSONObject content = new JSONObject();
        Map<String, String> mapParam = new HashMap<String, String>();
        boolean flag = userService.checkUpdateCourseShot(cname, desc_info, key);
        if (!flag) {
            dto.setDesc("必填项不能为空");
            dto.setStatus(MsgConst.UPDATE_COURSESHOT_NOT_NULL);
            dto.setSuccess(false);
        } else {
            mapParam.put("cid", cid);
            mapParam.put("cname", cname);
            mapParam.put("desc_info", desc_info);
            mapParam.put("img_url", img_url);
            mapParam.put("update_time", update_time);
            int ret = userService.updateCourseShot(mapParam);
            if (1 == ret) {
                content.put("cid", cid);
                content.put("name", cname);
                content.put("code", code);
                String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "修改了课程基本信息", "2", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
                dto.setData(img_url);
                dto.setDesc("修改成功");
                dto.setStatus(MsgConst.UPDATE_COURSESHOT_SUCCESS);
                dto.setSuccess(true);
            } else {
                dto.setDesc("修改失败");
                dto.setStatus(MsgConst.UPDATE_COURSESHOT_FAILED);
                dto.setSuccess(false);
            }
        }
        return dto;
    }


    @AuthCheck(Auth.NEED_LOGIN)
    @PostMapping("/manager/course/add")
    @ResponseBody
    public ResponseBaseDTO addCourseShot(@RequestBody JSONObject jo, HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        JSONObject data = jo.getJSONObject("data");
        String cname = data.getString("name");
        String cid = HashUtil.generateSerial(cname);
        String desc_info = data.getString("desc_info");
        String url = Const.DOMAIN + data.getString("key");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        DeviceInfo deviceInfo = IpUtil.getDeviceInfo(request);
        JSONObject content = new JSONObject();
        boolean flag = userService.checkAddCourseShot(cname, desc_info, url);
        if (!flag) {
            dto.setDesc("信息不全");
            dto.setStatus(MsgConst.ADD_COUSER_SHOT_FAILED);
            dto.setSuccess(false);
            return dto;
        } else {
            String code = null;
            if (userService.countCourseShot() > 0) {
                String max = userService.maxCourseShot();
                String xz = max.substring(0, 2);
                max = max.substring(2);
                int i = Integer.parseInt(max) + 1;
                String str = String.valueOf(i);
                code = xz + i;
            } else {
                code = "XZ1000001";
            }
            content.put("cid", cid);
            content.put("name", cname);
            content.put("code", code);
            Manager manager = userService.selectManagerById(uid);
            String uname = manager.getName();
            Map<String, String> mapParam = new HashMap<String, String>();
            mapParam.put("cid", cid);
            mapParam.put("cname", cname);
            mapParam.put("desc_info", desc_info);
            mapParam.put("img_url", url);
            mapParam.put("uid", uid);
            mapParam.put("code", code);
            mapParam.put("user_name", uname);
            String curTime = TimeUtil.getDateTime();
            mapParam.put("update_time", curTime);
            mapParam.put("create_time", curTime);
            int ret = userService.addCourseShot(mapParam);
            if (1 == ret) {
                String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "创建了一门课程", "1", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
                dto.setDesc("添加成功");
                dto.setData(cid);
                dto.setStatus(MsgConst.ADD_COUSER_SHOT_SUCCESS);
                dto.setSuccess(true);
            } else {
                dto.setDesc("添加失败");
                dto.setStatus(MsgConst.ADD_COUSER_SHOT_FAILED);
                dto.setSuccess(false);
            }
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/course/search")
    @ResponseBody
    public ResponseBaseDTO likeCourseShot(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cname = request.getParameter("keyword");
        if (StringUtils.isEmpty(cname)) {
            dto.setStatus(MsgConst.GET_COUSER_SEARCH_FAILED);
            dto.setSuccess(false);
        } else {
            Map<String, String> mapParam = new HashMap<String, String>();
            mapParam.put("cname", cname);
            List<CourseShot> listRet = userService.likeCourseShot(mapParam);
            PagedResult<CourseShot> pagedResult = BeanUtil.toPagedResult(listRet);
            dto.setData(pagedResult);
            dto.setDesc("获取课程列表成功");
            dto.setStatus(MsgConst.GET_COUSER_SEARCH_SUCCESS);
            dto.setSuccess(true);
        }
        return dto;
    }

    /*
     *
     * 1.0获取所有课程
     * */
    @GetMapping("/manager/course_m/get")
    @ResponseBody
    public ResponseBaseDTO getCourseFirstEdition(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        int page = StringUtils.isEmpty(pageStr) ? 1 : Integer.parseInt(pageStr);
        int size = StringUtils.isEmpty(sizeStr) ? 10 : Integer.parseInt(sizeStr);
        List<CourseGet> listRet = userService.getCourseFirstEdition(page, size, uid);
        PagedResult<CourseGet> pagedResult = BeanUtil.toPagedResult(listRet);
        dto.setData(pagedResult);
        dto.setDesc("获取课程列表成功");
        dto.setStatus(MsgConst.GET_COURSEFIRSTEDITION_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }

    @GetMapping("/manager/student/coursebyuid")
    @ResponseBody
    public ResponseBaseDTO selectByIdStudy(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String uid = request.getParameter("uid");
        List<String> list = userService.selectStudy(uid);
        List<CourseShot> shotList = new ArrayList<CourseShot>();
        for (String cid : list) {
            userService.selectByIdCourseShot(cid);
            shotList.add(userService.selectByIdCourseShot(cid));
        }
        dto.setData(shotList);
        dto.setDesc("获取课程列表成功");
        dto.setStatus(MsgConst.GET_COUSER_SHOT_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/course/switch")
    @ResponseBody
    public ResponseBaseDTO updateCourseShotStatus(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("cid");
        String status = request.getParameter("status");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        DeviceInfo deviceInfo = IpUtil.getDeviceInfo(request);
        JSONObject content = new JSONObject();
        CourseGet courseGet = userService.getCourseByCid(cid);
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("cid", cid);
        mapParam.put("status", status);
        int ret = cmsService.updateCourseShotStatus(mapParam);
        if (ret == 1) {
            content.put("cid", cid);
            content.put("name", courseGet.getCourse_name());
            content.put("code", courseGet.getCode());
            if (status.equals("1")) {
                String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "发布了一门课程", "5", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
            } else {
                String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "停用了一门课程", "6", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
            }
            dto.setDesc("操作成功");
            dto.setStatus(MsgConst.UPDATE_COURSESHOTSTATUS_SUCCESS);
            dto.setSuccess(true);
        } else {
            dto.setDesc("操作失败");
            dto.setStatus(MsgConst.UPDATE_COURSESHOTSTATUS_FAILED);
            dto.setSuccess(false);
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/teacher/search")
    @ResponseBody
    public ResponseBaseDTO likePersonage(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String name = request.getParameter("keyword");
        if (StringUtils.isEmpty(name)) {
            dto.setStatus(MsgConst.GET_TEACHER_SEARCH_FAILED);
            dto.setSuccess(false);
        } else {
            Map<String, String> mapParam = new HashMap<String, String>();
            mapParam.put("name", name);
            List<Personage> listRet = cmsService.likePersonage(mapParam);
            dto.setData(listRet);
            dto.setDesc("获取名师列表成功");
            dto.setStatus(MsgConst.GET_TEACHER_SEARCH_SUCCESS);
            dto.setSuccess(true);
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @PostMapping("/manager/modify")
    @ResponseBody
    public ResponseBaseDTO modifyManager(@RequestBody JSONObject jo,
                                         HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        JSONObject data = jo.getJSONObject("data");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        String name = data.getString("name");
        String phone_num = data.getString("phone_num");
        String email = data.getString("email");
        String img_url;
        String key = data.getString("key");
        if (StringUtils.isEmpty(key)) {
            img_url = null;
        } else {
            img_url = Const.DOMAIN + data.getString("key");
        }
        if (StringUtils.isEmpty(phone_num)) {
            phone_num = null;
        }
        if (StringUtils.isEmpty(email)) {
            email = null;
        }
        User user1 = userService.getUserByEmail(email);
        User user = userService.getUserByPhone(phone_num);
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("name", name);
        mapParam.put("uid", uid);
        mapParam.put("phone_num", phone_num);
        mapParam.put("email", email);
        mapParam.put("img_url", img_url);
        if (StringUtils.isEmpty(name)) {
            dto.setDesc("必填项不能为空");
            dto.setStatus(MsgConst.MODIFY_MANAGER_NOT_NULL);
            dto.setSuccess(false);
            return dto;
        }
        if (null == user && null == user1) {
            int ret = cmsService.modifyManager(mapParam);
            if (1 == ret) {
                dto.setData(img_url);
                dto.setDesc("修改成功");
                dto.setStatus(MsgConst.MODIFY_MANAGER_SUCCESS);
                dto.setSuccess(true);
            } else {
                dto.setDesc("服务器内部错误，请重试");
                dto.setStatus(MsgConst.MODIFY_MANAGER_ERROR);
                dto.setSuccess(false);
            }
        } else {
            if (null == user && null != user1) {
                if (user1.getUid().equals(uid)) {
                    int ret = cmsService.modifyManager(mapParam);
                    if (1 == ret) {
                        dto.setData(img_url);
                        dto.setDesc("修改成功");
                        dto.setStatus(MsgConst.MODIFY_MANAGER_SUCCESS);
                        dto.setSuccess(true);
                    } else {
                        dto.setDesc("服务器内部错误，请重试");
                        dto.setStatus(MsgConst.MODIFY_MANAGER_ERROR);
                        dto.setSuccess(false);
                    }
                } else {
                    dto.setDesc("该邮箱已绑定,请更换邮箱绑定！");
                    dto.setStatus(MsgConst.MODIFY_MANAGER_EXIST);
                    dto.setSuccess(false);
                }
            } else if (null == user1 && null != user) {
                if (user.getUid().equals(uid)) {
                    int ret = cmsService.modifyManager(mapParam);
                    if (1 == ret) {
                        dto.setData(img_url);
                        dto.setDesc("修改成功");
                        dto.setStatus(MsgConst.MODIFY_MANAGER_SUCCESS);
                        dto.setSuccess(true);
                    } else {
                        dto.setDesc("服务器内部错误，请重试");
                        dto.setStatus(MsgConst.MODIFY_MANAGER_ERROR);
                        dto.setSuccess(false);
                    }
                } else {
                    dto.setDesc("该手机号已绑定,请更换手机号绑定！");
                    dto.setStatus(MsgConst.MODIFY_MANAGER_EXIST);
                    dto.setSuccess(false);
                }
            } else if (user.getUid().equals(uid) && user1.getUid().equals(uid)) {
                int ret = cmsService.modifyManager(mapParam);
                if (1 == ret) {
                    dto.setData(img_url);
                    dto.setDesc("修改成功");
                    dto.setStatus(MsgConst.MODIFY_MANAGER_SUCCESS);
                    dto.setSuccess(true);
                } else {
                    dto.setDesc("服务器内部错误，请重试");
                    dto.setStatus(MsgConst.MODIFY_MANAGER_ERROR);
                    dto.setSuccess(false);
                }
            } else {
                dto.setDesc("该手机号和邮箱都已绑定");
                dto.setStatus(MsgConst.MODIFY_MANAGER_EXIST);
                dto.setSuccess(false);
            }
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @PostMapping("/manager/password/update")
    @ResponseBody
    public ResponseBaseDTO updatePassword(@RequestBody JSONObject jo, HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        JSONObject data = jo.getJSONObject("data");
        String oldpwd = data.getString("oldpwd");
        String newpwd = data.getString("newpwd");
        String confirmpwd = data.getString("confirmpwd");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("oldpwd", oldpwd);
        mapParam.put("newpwd", newpwd);
        mapParam.put("confirmpwd", confirmpwd);
        mapParam.put("uid", uid);
        boolean flag = userService.checkPassword(oldpwd, newpwd, confirmpwd);
        if (!flag) {
            dto.setDesc("必填项不能为空");
            dto.setStatus(MsgConst.UPDATE_MANAGERPWD_NOT_NULL);
            dto.setSuccess(false);
            return dto;
        }
        if (cmsService.getManagerPwdByuid(uid).equals(oldpwd)) {
            if (cmsService.getManagerPwdByuid(uid).equals(newpwd)) {
                dto.setDesc("新密码跟旧密码不能相同！！！");
                dto.setStatus(MsgConst.UPDATE_MANAGERPWD_SAME);
                dto.setSuccess(false);
            } else {
                if (newpwd.equals(confirmpwd)) {
                    int ret = cmsService.updateManagerPassword(mapParam);
                    if (ret == 1) {
                        dto.setDesc("修改成功");
                        dto.setStatus(MsgConst.UPDATE_MANAGERPWD_SUCCESS);
                        dto.setSuccess(true);
                    } else {
                        dto.setDesc("修改失败");
                        dto.setStatus(MsgConst.UPDATE_MANAGERPWD_ERROR);
                        dto.setSuccess(false);
                    }
                } else {
                    dto.setDesc("两次输入的密码不相同");
                    dto.setStatus(MsgConst.UPDATE_MANAGERPWD_DIFPWD);
                    dto.setSuccess(false);
                }
            }
        } else {
            dto.setDesc("你输入的旧密码错误");
            dto.setStatus(MsgConst.UPDATE_MANAGERPWD_OLDPWDERROR);
            dto.setSuccess(false);
        }
        return dto;
    }


    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/course/del")
    @ResponseBody
    public ResponseBaseDTO removeCourse(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("cid");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        DeviceInfo deviceInfo = IpUtil.getDeviceInfo(request);
        JSONObject content = new JSONObject();
        CourseGet courseGet = userService.getCourseByCid(cid);
        if (cmsService.existStudy(cid)) {
            dto.setDesc("该课程被学生学习过，需要后继备案，尚不能做删除，只能到下架状态");
            dto.setStatus(MsgConst.DEL_COURSE_FAILED);
            dto.setSuccess(false);
        } else {
            int ret = cmsService.removeCourse(cid);
            if (ret == 1) {
                content.put("cid", cid);
                content.put("name", courseGet.getCourse_name());
                content.put("code", courseGet.getCode());
                String[] keys1 = {"guid", "uid", "content", "comment", "type", "ip", "system", "device", "role_type", "create_time"};
                String[] vals1 = {HashUtil.generateSerial(uid), uid, content.toString(), "删除了一门课程", "4", deviceInfo.getIp(), deviceInfo.getSystem(), deviceInfo.getBrowser(), "1", TimeUtil.getDateTime()};
                userService.addUserBehaviour(DataUtil.generateMap(keys1, vals1));
                dto.setDesc("删除成功");
                dto.setStatus(MsgConst.DEL_COURSE_SUCCESS);
                dto.setSuccess(true);
            } else {
                dto.setDesc("删除失败");
                dto.setStatus(MsgConst.DEL_COURSE_FAILED);
                dto.setSuccess(false);
            }
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/getonebyuid")
    @ResponseBody
    public ResponseBaseDTO getManagerOneByUid(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        Manager manager = cmsService.getManagerOneByUid(uid);
        dto.setData(manager);
        dto.setStatus(MsgConst.GET_MANAGERONE_SUCCESS);
        dto.setSuccess(true);
        dto.setDesc("获取管理员资料成功");
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/account/record")
    @ResponseBody
    public ResponseBaseDTO getAdminActionRecord(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String name = request.getParameter("name");
        String nickname = request.getParameter("nickname");
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        int page = StringUtils.isEmpty(pageStr) ? 1 : Integer.parseInt(pageStr);
        int size = StringUtils.isEmpty(sizeStr) ? 10 : Integer.parseInt(sizeStr);
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("name", name);
        mapParam.put("nickname", nickname);
        mapParam.put("starttime", starttime);
        mapParam.put("endtime", endtime);
        List<Record> listRet = cmsService.getAdminActionRecord(mapParam, page, size);
        PagedResult<Record> pagedResult = BeanUtil.toPagedResult(listRet);
        dto.setData(pagedResult);
        dto.setDesc("获操作记录成功");
        dto.setStatus(MsgConst.GET_ALL_COURSCMS_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/open/record")
    @ResponseBody
    public ResponseBaseDTO getStudy(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String uid = request.getParameter("uid");
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        int page = StringUtils.isEmpty(pageStr) ? 1 : Integer.parseInt(pageStr);
        int size = StringUtils.isEmpty(sizeStr) ? 10 : Integer.parseInt(sizeStr);
        List<Study> listRet = cmsService.getStudy(page, size, uid);
        PagedResult<Study> pagedResult = BeanUtil.toPagedResult(listRet);
        dto.setData(pagedResult);
        dto.setStatus(MsgConst.GET_OPEN_RECORD_SUCCESS);
        dto.setSuccess(true);
        dto.setDesc("获取开通记录成功");
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/getonebyid")
    @ResponseBody
    public ResponseBaseDTO getStudentOneByUid(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String uid = request.getParameter("uid");
        LmsService lmsService;
        StudentOne studentOne = cmsService.getStudentOneByUid(uid);
        dto.setData(studentOne);
        dto.setStatus(MsgConst.GET_STUDENTONEBYID_SUCCESS);
        dto.setSuccess(true);
        dto.setDesc("获取学生资料成功");
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/stu/course/del")
    @ResponseBody
    public ResponseBaseDTO delectStudyOne(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String cid = request.getParameter("cid");
        String uid = request.getParameter("uid");
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("cid", cid);
        mapParam.put("uid", uid);
        int ret = cmsService.delectStudyOne(mapParam);
        if (ret == 1) {
            dto.setDesc("删除成功");
            dto.setStatus(MsgConst.DEL_STU_COURSE_SUCCESS);
            dto.setSuccess(true);
        } else {
            dto.setDesc("删除失败");
            dto.setStatus(MsgConst.DEL_STU_COURSE_FAILED);
            dto.setSuccess(false);
        }

        return dto;
    }

    @PostMapping("/qa/encrypt/info")
    public void qiniuCallBackEncrypt(@RequestBody JSONObject jo) throws Exception {
        System.out.println("qiniuCallBack : " + jo.toJSONString());
        System.out.println(jo.getString("code"));
        String sourceKey = jo.getString("inputKey");
        JSONArray jaItem = jo.getJSONArray("items");
        if (null == jaItem) return;
        else {
            for (Object one : jaItem) {
                String code = ((JSONObject) one).getString("code");
                String key = ((JSONObject) one).getString("key");
                System.out.println("key : " + key + ", code : " + code);
                if ("0".equals(code)) {
                    cmsService.updateCourseVideoEncryptStatusOk(key);
                } else {
                    if (null == key) {
                        String sourceUrl = "http://pb2grd34a.bkt.clouddn.com/" + sourceKey; //TODO 未来从配置文件入手
                        List<CourseEncrypt> listCourse = cmsService.getCourseByEncryptkeyByUrl(sourceUrl);
                        if (listCourse.size() == 1) {
                            Map<String, String> mapParam = new HashMap<String, String>();
                            mapParam.put("key", listCourse.get(0).getEncrypt_key()); //TODO 未来从配置文件入手
                            mapParam.put("err_count", String.valueOf(Integer.parseInt(listCourse.get(0).getErr_count()) + 1));
                            cmsService.updateCourseVideoEncryptStatusFail(mapParam);
                        }
                        // 测试等于密码没有base64导致的加密出错，这个时候没有key出来
                    } else {
                        List<CourseEncrypt> listCourse = cmsService.getCourseByEncryptkey(key);
                        if (listCourse.size() == 1) {
                            Map<String, String> mapParam = new HashMap<String, String>();
                            mapParam.put("encrypt_key", key);
                            mapParam.put("err_count", String.valueOf(Integer.parseInt(listCourse.get(0).getErr_count())) + 1);
                            cmsService.updateCourseVideoEncryptStatusFail(mapParam);
                        } else {
                            System.out.println("wrong encrypt key, key : " + key);
                        }
                    }

                }
            }
        }
    }


    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/stuname/search")
    @ResponseBody
    public ResponseBaseDTO likeStudentName(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String name = request.getParameter("name");
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        int page = StringUtils.isEmpty(pageStr) ? 1 : Integer.parseInt(pageStr);
        int size = StringUtils.isEmpty(sizeStr) ? 10 : Integer.parseInt(sizeStr);
        if (StringUtils.isEmpty(name)) {
            dto.setStatus(MsgConst.GET_COUSER_STUDENT_NAME_FAILED);
            dto.setSuccess(false);
        } else {
            List<Student> listRet = userService.likeStudentName(name, page, size);
            PagedResult<Student> pagedResult = BeanUtil.toPagedResult(listRet);
            dto.setData(pagedResult);
            dto.setDesc("获取学员列表成功");
            dto.setStatus(MsgConst.GET_COUSER_STUDENT_NAME_SUCCESS);
            dto.setSuccess(true);
        }
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("/manager/course_shot/lname")
    @ResponseBody
    public ResponseBaseDTO getCourseShotLikeName(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        String cname = request.getParameter("cname");
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        int page = StringUtils.isEmpty(pageStr) ? 1 : Integer.parseInt(pageStr);
        int size = StringUtils.isEmpty(sizeStr) ? 10 : Integer.parseInt(sizeStr);
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("uid", uid);
        mapParam.put("cname", cname);
        List<CourseGet> listRet = cmsService.getCourseShotLikeName(page, size, mapParam);
        PagedResult<CourseGet> pagedResult = BeanUtil.toPagedResult(listRet);
        dto.setData(pagedResult);
        dto.setDesc("获取课程列表成功");
        dto.setStatus(MsgConst.GET_COURSE_SHOT_LILE_NAME_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }

    @AuthCheck(Auth.NEED_LOGIN)
    @GetMapping("manager/import/course")
    @ResponseBody
    public ResponseBaseDTO importcourzse(HttpServletRequest request) throws Exception {
        ResponseBaseDTO dto = new ResponseBaseDTO();
        String current_cid = request.getParameter("current_cid");
        String import_cid = request.getParameter("import_cid");
        String uid = tokenUtil.getProperty(request.getHeader("ACCESS_TOKEN"), "uid");
        Map<String, String> mapParam = new HashMap<String, String>();
        mapParam.put("uid", uid);
        mapParam.put("cid", current_cid);
        if (current_cid.equals(import_cid)) {
            dto.setDesc("导入课程与本课程相同，不能导入");
            dto.setStatus(MsgConst.IMPORT_COURSE_SUCCESS);
            dto.setSuccess(false);
            return dto;
        }
        cmsService.delCourseWare(current_cid);
        cmsService.delCourseWareRelation(current_cid);
        Manager manager = userService.selectManagerById(uid);
        CourseShotImport csi = cmsService.getTnumTlen(import_cid);
        String uname = manager.getName();
        mapParam.put("user_name", uname);
        mapParam.put("total_num", csi.getTotal_num());
        mapParam.put("total_len", csi.getTotal_len());
        String catalog = userService.getCatalog(import_cid);
        JSONArray ja = JSONArray.parseArray(catalog);
        for (Object one : ja) {
            JSONArray cja = ((JSONObject) one).getJSONArray("children");
            System.out.println("children:"+cja);
            if (cja == null || cja.size() == 0) {
                String id = ((JSONObject) one).getString("id");
                CourseWareRelation cwr = cmsService.getCourseWareRelation(id);
                if (cwr == null) {
                    String new_id = HashUtil.generateSerial(id);
                    ((JSONObject) one).put("id", new_id);
                } else {
                    CourseWareModel cw = cmsService.getCourseWareByWareId(cwr.getWare_id());
                    String new_id = HashUtil.generateSerial(id);
                    String new_ware_id = HashUtil.generateSerial(cwr.getWare_id());
                    ((JSONObject) one).put("id", new_id);
                    mapParam.put("node_id", new_id);
                    mapParam.put("desc_info", cwr.getDesc_info());
                    mapParam.put("update_time", TimeUtil.getDateTime());
                    mapParam.put("create_time", TimeUtil.getDateTime());
                    mapParam.put("ware_id", new_ware_id);
                    mapParam.put("ware_name", cw.getWare_name());
                    mapParam.put("url", cw.getUrl());
                    mapParam.put("len", cw.getLen());
                    mapParam.put("type", cw.getType());
                    mapParam.put("comment", cw.getComment());
                    mapParam.put("encrypt_key", cw.getEncrypt_key());
                    mapParam.put("encrypt_pwd", cw.getEncrypt_pwd());
                    mapParam.put("encrypt_time", cw.getEncrypt_time());
                    mapParam.put("step", cw.getStep());
                    mapParam.put("err_count", cw.getErr_count());
                    userService.addNodeDetail(mapParam);
                    cmsService.addCoursewWare(mapParam);
                }
            } else {
                for (Object two : cja) {
                    JSONArray cja1 = ((JSONObject) two).getJSONArray("children");
                    System.out.println("cja1:"+cja1);
                    System.out.println(cja1.equals("[]"));
                    if (cja1 == null || cja1.size() == 0) {
                        String id = ((JSONObject) two).getString("id");
                        CourseWareRelation cwr = cmsService.getCourseWareRelation(id);
                        if (cwr == null) {
                            String new_id = HashUtil.generateSerial(id);
                            ((JSONObject) two).put("id", new_id);
                        } else {
                            CourseWareModel cw = cmsService.getCourseWareByWareId(cwr.getWare_id());
                            String new_id = HashUtil.generateSerial(id);
                            String new_ware_id = HashUtil.generateSerial(cwr.getWare_id());
                            ((JSONObject) two).put("id", new_id);
                            mapParam.put("node_id", new_id);
                            mapParam.put("desc_info", cwr.getDesc_info());
                            mapParam.put("update_time", TimeUtil.getDateTime());
                            mapParam.put("create_time", TimeUtil.getDateTime());
                            mapParam.put("ware_id", new_ware_id);
                            mapParam.put("ware_name", cw.getWare_name());
                            mapParam.put("url", cw.getUrl());
                            mapParam.put("len", cw.getLen());
                            mapParam.put("type", cw.getType());
                            mapParam.put("comment", cw.getComment());
                            mapParam.put("encrypt_key", cw.getEncrypt_key());
                            mapParam.put("encrypt_pwd", cw.getEncrypt_pwd());
                            mapParam.put("encrypt_time", cw.getEncrypt_time());
                            mapParam.put("step", cw.getStep());
                            mapParam.put("err_count", cw.getErr_count());
                            userService.addNodeDetail(mapParam);
                            cmsService.addCoursewWare(mapParam);
                        }
                    } else {
                        for (Object three : cja1) {
                            String id = ((JSONObject) three).getString("id");
                            CourseWareRelation cwr = cmsService.getCourseWareRelation(id);
                            if (cwr == null ) {
                                String new_id = HashUtil.generateSerial(id);
                                ((JSONObject) three).put("id", new_id);
                            } else {
                                CourseWareModel cw = cmsService.getCourseWareByWareId(cwr.getWare_id());
                                String new_id = HashUtil.generateSerial(id);
                                String new_ware_id = HashUtil.generateSerial(cwr.getWare_id());
                                ((JSONObject) three).put("id", new_id);
                                mapParam.put("node_id", new_id);
                                mapParam.put("desc_info", cwr.getDesc_info());
                                mapParam.put("update_time", TimeUtil.getDateTime());
                                mapParam.put("create_time", TimeUtil.getDateTime());
                                mapParam.put("ware_id", new_ware_id);
                                mapParam.put("ware_name", cw.getWare_name());
                                mapParam.put("url", cw.getUrl());
                                mapParam.put("len", cw.getLen());
                                mapParam.put("type", cw.getType());
                                mapParam.put("comment", cw.getComment());
                                mapParam.put("encrypt_key", cw.getEncrypt_key());
                                mapParam.put("encrypt_pwd", cw.getEncrypt_pwd());
                                mapParam.put("encrypt_time", cw.getEncrypt_time());
                                mapParam.put("step", cw.getStep());
                                mapParam.put("err_count", cw.getErr_count());
                                userService.addNodeDetail(mapParam);
                                cmsService.addCoursewWare(mapParam);
                            }
                        }
                    }
                }
            }
        }
        catalog = JSONArray.toJSONString(ja);
        System.out.println(catalog);
        mapParam.put("catalog", catalog);
        int ret = cmsService.updateCourseShot(mapParam);
        dto.setDesc("导入成功");
        dto.setStatus(MsgConst.IMPORT_COURSE_SUCCESS);
        dto.setSuccess(true);
        return dto;
    }
}